<?php

namespace app\admin\services;

use think\App;
use think\Service;
use think\facade\Config;
use think\facade\Request;
use think\facade\Session;
use app\admin\model\AdminUserModel;
use app\admin\model\LoginlogModel;
use app\admin\model\AuthgroupModel;
use think\facade\Cache;
class InoutService extends Service
{
    public function __construct(Request $request = null, App $app = null)
    {
        $this->AdminUserModel = new AdminUserModel();
        $this->LoginlogModel = new LoginlogModel();
        $this->AuthgroupModel = new AuthgroupModel();
        parent::__construct($request, $app);
    }

    /**
     * 登陆接口
     */
    public function adminLogin()
    {
        if(!Request::isPost()){
            return $this->_getResponse("NO_POST");
        }
        $username = Request::param("username");
        $password = Request::param("password");
        $yan = Request::param("yan");
        if (!$password || !$username) {
            return $this->_getResponse("PARAM_EORRE");      //参数错误
        }

        if(!captcha_check($yan)){
            return $this->_getResponse('YZMA_ERROR');
        }

        //加密字符
        $confighd = Config::get('ADMIN_HEADER');
        $configft = Config::get('ADMIN_FOOTER');
        $where = [
            ['username', '=', $username],
            ['password', '=', md5($confighd . $password . $configft)]
        ];

        $result = $this->AdminUserModel->findPw($where);
        if (!$result) {
            return $this->_getResponse("USER_EORRE"); //用户名或密码错误
        }

        if ($result['disable'] == 2) {
            return $this->_getResponse("USER_DISABLE"); //用户已禁用
        }

        if($result['isdelete']==2){
            return $this->_getResponse("USER_DELETE"); //用户已删除
        }

        if($username == 'admin'){
            $adminmanualgroup = new \app\admin\services\AdminManuakGroupService();
            $manual = $adminmanualgroup->getParentData();
            $result['manual']='';
            foreach ($manual as $k=>$v){
                $result['manual'].=$v['id'].',';
            }
            $result['manual'] = substr($result['manual'],0,strlen($result['manual'])-1);
        }
        $session_id = session_id();
        Session::set('username', $username, 'admin');
        Session::set('sessionid', $session_id, 'admin');
        Session::set('uid', $result['id'], 'admin');//用户id
        Session::set('position', $result['position'], 'admin');//用户职位
        Session::set('authgroup', $result['authgroup'], 'admin'); //权限组
        Session::set('special', $result['special'], 'admin');  //账号特殊组
        Session::set('manual', $result['manual'], 'admin');
        Session::set('Versiontype', $result['Versiontype'], 'admin'); //账号分类
        $key = 'login_id'.$result['id'];
        $value = $session_id;
        $eopri = 1800;
        $idsr = Cache::store('redis')->has($key);
        $data = [
            'session_id'=> $session_id,
            'loginTime' => date('Y-m-d H:i:s',time()),
            'loginIp' => getIp()
        ];
        $uid = Session::get('uid','admin');
        $typeid = Session::get('authgroup','admin');
        $where = [['id','eq',$typeid]];
        $leixing = $this->AuthgroupModel->usertype($where);
        $updata = $this->AdminUserModel->Upuserlist($uid,$data);//更新登录信息
        if(!$updata){
            return $this->_getResponse('LOGIN_ERROR');
        }
        $log['loginTime'] = time();
        $log['loginIp'] = getIp();
        $log['uid'] = $uid;
        $log['username'] = Session::get('username','admin');
        $log['accessTime']=date('Y-m-d H:i:s',time());
        $log['isOnLine']=1;
        $log['usertype'] = $leixing['title'];
        $log['stintg'] = opstion(Session::get('position','admin'));
        $addlog = $this->LoginlogModel->log($log);
        if(!$addlog){
            return $this->_getResponse('LOGIN_NO');
        }
        Cache::store('redis')->set($key,$value,$eopri); //写入缓存
        if($idsr!=false){
            return $this->_getResponse('USER_ERROR');
        }else{
            return $this->_getResponse("LOGIN_SUCESS");
        }
    }


    /**
     * 后台退出
     */
    public function adminOut()
    {
        $id = Session::get('uid','admin');
        $key = 'login_id'.$id;
        Cache::store('redis')->rm($key);
        $result = Session::clear('admin');
        if ($result) {
            return $this->_getResponse("LOGINERRO"); //未知错误
        }
        return $this->_getResponse("LOGINOUT");
    }

    /**
     * @param $key
     * @param array $data
     * @return mixed
     */
    protected function _getResponse($key, $data = [])
    {
        $maps = [
            "SUCCESS" => ["status" => 0, "msg" => "sccuess", "data" => $data],
            "LOGIN_SUCESS" => ["status" => 0, "msg" => "登录成功", "data" => $data],
            "LOGINOUT" => ["status" => 0, "msg" => "退出成功", "data" => $data],
            "PARAM_EORRE" => ["status" => 1, "msg" => "参数错误", "data" => $data],
            "NUKNOW_EORRE" => ["status" => 2, "msg" => "未知错误", "data" => $data],
            "LOGINERRO" => ["status" => 2, "msg" => "退出失败", "data" => $data],
            "USER_EORRE" => ["status" => 3, "msg" => "用户名或密码错误", "data" => $data],
            "USER_DISABLE" => ["status" => 4, "msg" => "用户已禁用", "data" => $data],
            "YZMA_ERROR" => ["status" => 5, "msg" => "验证码错误", "data" => $data],
            "USER_DELETE" => ["status" => 6, "msg" => "用户不存在", "data" => $data],
            "NO_POST" => ["status" => 7, "msg" => "非法请求", "data" => $data],
            "LOGIN_ERROR" => ["status" => 8, "msg" => "异常登录", "data" => $data],
            "LOGIN_NO" => ["status" => 9, "msg" => "登录异常", "data" => $data],
            "USER_ERROR" => ["status" => 0, "msg" => "警告，该用户正在登陆请尽快修改密码", "data" => $data]
        ];
        return $maps[$key];
    }

}